package com.demo.controller;

import com.demo.aop.AuthorizationRequired;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.BusinessException;
import com.demo.core.exception.ParameterException;
import com.demo.domain.TeamComposition;
import com.demo.domain.TeamCompositionRequest;
import com.demo.service.TeamCompositionService;
import com.demo.utils.PageBean;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teamComposition")
public class TeamCompositionController {
    @Autowired
    TeamCompositionService teamCompositionService;

    @Autowired
    PracticalAchievementController practicalAchievementController;



    /**
     * 根据队伍id获取对应队伍的组成信息
     *
     * @param teamId
     * @return
     * @throws IOException
     */
    @Operation(summary = "获取队伍的组成信息")
    @GetMapping(value = "/display")
    public Result getTeamComposition(@RequestParam("teamId") long teamId) throws IOException, ParameterException {
        if (teamId <= 0l) {
            throw new ParameterException("参数teamId数值非法");
        }
        TeamComposition teamComposition = new TeamComposition();
        teamComposition.setTeamId(teamId);
        List<TeamComposition> teamCompositionMemberList = teamCompositionService.getTeamMember(teamComposition);
        return teamCompositionMemberList != null && !teamCompositionMemberList.isEmpty()?
                Result.success(HttpStatus.SUCCESS, "获取数据成功", teamCompositionMemberList):
                Result.success(HttpStatus.NOT_FOUND, "No team composition found.", null);
    }

    /**
     * 删除指定队伍中的指定队员的信息
     * @param teamComposition
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "删除队员")
    @PostMapping(value = "/deleTeamMember")
    public Result deleTeamMember(@RequestBody TeamComposition teamComposition,HttpServletRequest request) throws ParameterException {
        Long teamId = teamComposition.getTeamId();
        Long memberId = teamComposition.getUid();
        String urealname = teamComposition.getUrealname();
        if (teamId == null || teamId <= 0l ||
                memberId == null || memberId <= 0l) {
            throw new ParameterException("参数teamId、uid非法或为null");
        }
        if (urealname == null || urealname.equals("")) {
            throw new ParameterException("参数urealname为null");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        boolean flag = false;
        if (teamId != null && urealname != null && uid != null) {
            flag = teamCompositionService.deleTeamMember(teamId, urealname, memberId,uid);
        }
        return flag ? Result.success(HttpStatus.NO_CONTENT, "删除成功", null)
                : Result.error("删除失败");
    }

    /**
     * 添加指定队伍中的指定队员的信息
     * @param teamCompositions
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "添加队员")
    @PostMapping(value = "/increTeamMember")
    public Result increTeamMember(@RequestBody List<TeamComposition> teamCompositions,HttpServletRequest request) throws ParameterException {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        boolean flag = false;
        for(TeamComposition teamComposition:teamCompositions){
            if(teamComposition.getMemberType()==1){
                throw new BusinessException(HttpStatus.CONFLICT,"队伍已有队长，队伍成员不能再任命为队长");
            }
            if (teamComposition.getTeamId() != null && teamComposition.getUid() != null && teamComposition.getUrealname()!=null && uid != null) {
                flag = teamCompositionService.increTeamMember(teamComposition,uid);
            }
        }
        return flag ? Result.success(HttpStatus.SUCCESS, "添加成功", null)
                : Result.error("添加失败");
    }

    /*
    组队相关的增删查改
    * */

//    @AuthorizationRequired
    @Operation(summary="根据id找队伍组成")
    @GetMapping("/search")
    public Result getByTcId(@RequestParam("tcId") Long tcId,HttpServletRequest request) throws ParameterException {
        return Result.success(HttpStatus.SUCCESS,"查找成功",teamCompositionService.getByTcId(tcId));
    }

    @Operation(summary="新增队伍组成")
    @PostMapping("/add")
    public Result add(@RequestBody TeamComposition teamComposition,HttpServletRequest request) throws ParameterException {
        Integer rows =  teamCompositionService.insertTeamComposition(teamComposition);
        return rows > 0 ? Result.success("添加队伍组成成功"):Result.error("添加队伍组成失败");
    }

    @Operation(summary="修改队伍组成")
    @PostMapping("/edit")
    public Result edit(@RequestBody TeamComposition teamComposition,HttpServletRequest request) throws ParameterException {
        int rows = teamCompositionService.updateTeamComposition(teamComposition);
        return rows > 0 ? Result.success("修改队伍组成成功"):Result.error("修改队伍组成失败");
    }


    @Operation(summary="删除队伍组成")
    @PostMapping ("/delete")
    public Result remove(@RequestBody List<TeamComposition> teamCompositions,HttpServletRequest request) throws ParameterException {
        int row = 0;
        int length = teamCompositions.size();
        for(TeamComposition teamComposition:teamCompositions){
            row += teamCompositionService.deleteTeamCompositionById(teamComposition);
        }
        return row ==length ? Result.success("删除队伍组成成功") : Result.error("删除队伍组成失败");
    }

    @GetMapping("/page")
    @Operation(summary="分页搜索")
    public  Result page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize")Integer pageSize,TeamComposition teamComposition) throws ParameterException {
        List<TeamComposition> list = null;
        PageBean<TeamComposition> info = new PageBean<>();
        if(teamComposition.getUid() !=null || teamComposition.getUrealname() !=null || teamComposition.getTeamId()!=null){
            list = teamCompositionService.selectTeamCompositionList(teamComposition);
        }else{
            list =  teamCompositionService.listAllTeamComposition();
        }
        System.out.println("list"+list);
        // 对查询结果进行分页处理
        PageInfo<TeamComposition> pageInfo = new PageInfo<>(list);
        int total = (int) pageInfo.getTotal();
        // 计算起始索引和结束索引
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);
        // 提取当前页的数据
        List<TeamComposition> pageList = list.subList(startIndex, endIndex);
        // 设置 PageBean 对象的属性
        info.setPageList(pageList);
        info.setPageNumber(pageNum);
        info.setPageSize(pageSize);
        info.setTotal(total);
        info.setTotalPage((total + pageSize - 1) / pageSize); // 计算总页数
        return Result.success(info);
    }
}
